import {createAsyncThunk, createSlice, PayloadAction, nanoid} from "@reduxjs/toolkit";
import axios, {shuffle as shuffleArr, Treading} from '../../utils'

export interface Trending {
  id: string
  title: string
}

interface ITrendingResp {
  success: boolean,
  data: string[]
}

export const getTrending = createAsyncThunk(
  'trending/get',
  async () => {
    const {data} = await axios.get<ITrendingResp>(Treading.GET)
    return data.data
  }
)

// 热搜
export const trendingSlice = createSlice({
  name: 'trending',
  initialState: [] as Trending[],
  reducers: {
    shuffle: state => shuffleArr(state)
  },
  extraReducers: (builder => {
    builder.addCase(getTrending.fulfilled, (state, action: PayloadAction<string[]>) => action.payload.map(item => ({
      id: nanoid(),
      title: item
    })));
  })
})

export const {shuffle} = trendingSlice.actions;
